import numpy as np
from scipy.optimize import leastsq
import matplotlib.pyplot as plt
from os import path
from pandas import DataFrame
import pandas as pd


def lineLogic():
    def func(startParam, x):
        a, b = startParam
        return a * x + b

    def error(startParam, x, y, s):
        print("error s : ", s)
        return func(startParam, x) - y

    X = np.array([8.19, 2.72, 6.39, 8.71, 4.7])
    Y = np.array([7.01, 2.78, 6.47, 6.71, 4.1])
    p = [10, 2]

    Para = leastsq(error, p, args=(X, Y, 'times'))
    print(Para)
    k, b = Para[0]
    print('k,b = {0},{1}'.format(k, b))

    # plt.figure(figsize=(8, 6))
    plt.scatter(X, Y)
    xx = np.linspace(0, 10, 100)
    yy = k * xx + b
    plt.plot(xx, yy, color='orange')
    # plt.legend()

    plt.show()


def noise():
    d = path.dirname(__file__)
    k = np.random.rand(40)
    print(d + '/w.txt')
    lk = k.tolist()
    with open(d + '/random.txt', mode='w') as f:
        for i in lk:
            f.write(str(i))
            f.write('\n')


def lg():
    k = []
    with open(path.dirname(__file__) + '/random.txt', mode='r') as f:
        for oo in range(16):
            k.append(float(f.readline()))

    k = np.asarray(k)
    x_list = np.arange(4, 20, 1)
    y_list = x_list * 3 + 8 + k
    print(k, k.mean(axis=0))
    print(x_list, y_list, sep='\n')

    def func(p, x):
        a, b = p
        return a * x + b;

    def error(p, x, y):
        # print(s)
        return func(p, x) - y

    def error1(param_tuple, x, y):
        # a, b =param_tuple
        return param_tuple[0] * x + param_tuple[1] - y

    p = (1, 1)

    k = leastsq(error, p, args=(x_list, y_list))
    print(k)
    a, b = k[0]
    plt.scatter(x_list, y_list, edgecolors='blue')
    x1 = np.linspace(-10, 30, 200)
    y1 = a * x1 + b
    plt.plot(x1, y1, color='red')
    plt.show()


def lg2():
    result = []
    with open(path.dirname(__file__) + '/random.txt') as f:
        while True:
            n = f.readline()
            if not n:
                break
            result.append(float(n))
            print(n)
    r = np.asarray(result)
    # r = r * 5
    X = np.arange(-10, 10, 2)
    Y = X * 3 + 5 + r[:len(X)] * 10
    print(r * 10)
    print(r[len(X)])
    print(X, Y)

    min = leastsq((lambda s, x, y_: s[0] * x + s[1] - y_)
                  , [2, 3]
                  , args=(X, Y))
    print(min)
    p = min[0]
    print(type(p))

    plt.scatter(X, Y, edgecolors='blue')

    xline = np.linspace(-10, 10, 200)

    plt.plot(xline, xline * p[0] + p[1])
    plt.show()


def rg2():
    target = '/home/xieweig/document/ss.xlsx'
    df = pd.read_excel(target, sheet_name=0, header=0)
    print(df)

    # print(df['x'],df['y'],sep='\n\n')
    # print(type(df['x']))
    all: DataFrame = df[['x', 'y']]
    a: np.ndarray = all.values
    # print(xxx,type(xxx))
    print(a, type(a))
    # print(a[1])
    xxx: np.ndarray = df['x'].values
    yyy: np.ndarray = df['y'].values
    print(xxx, yyy, sep='\n')
    r = leastsq(
        lambda s, x, y_: s[0] * x + s[1] - y_,
        np.asarray([1, 1]), (xxx, yyy))
    print(r)
    k = r[0][0]
    print('k= ', k)
    b = r[0][1]
    print('b= ', b)

    plt.scatter(xxx, yyy)
    z = np.linspace(0, 30, 1000)
    plt.plot(z, k * z + b)
    plt.show()


def rg3():
    s1 = lambda x: np.cos(x)
    s2 = lambda x: np.cos(x) + 3 * np.cos(3 * x)
    s3 = lambda x: np.cos(x) + 3 * np.cos(3 * x) + 5 * np.cos(5 * x)

    s4 = lambda x: np.cos(x) + 3 * np.cos(3 * x) + 5 * np.cos(5 * x) + 7 * np.cos(7 * x)
    x=np.linspace(-5,5,1000)
    f: plt.Figure = plt.figure(1)
    ax1:plt.Axes=f.add_subplot(221)
    ax1.scatter(x,s1(x))
    ax2:plt.Axes=f.add_subplot(222)
    ax2.scatter(x,s2(x))
    ax3:plt.Axes=f.add_subplot(223)
    ax3.scatter(x,s3(x))
    ax4:plt.Axes=f.add_subplot(224)
    ax4.scatter(x,s4(x))

    f.show()
    # plt.imsave('/home/xieweig/document/fft.png')

    f.savefig('/home/xieweig/document/fft.png',dpi=600)

def rg4():
    target = '/home/xieweig/document/self.xlsx'
    dest='/home/xieweig/document/self.csv'
    df =pd.read_excel(target,sheet_name=0,header=0)
    print(df)

    df.to_csv(dest,index=False)


if __name__ == '__main__':
    # lineLogic()
    rg4()

    # noise()
